//suggust 控件中使用
var UI = {
	keyCode: {
		ENTER: 13, ESC: 27, END: 35, HOME: 36,
		SHIFT: 16, TAB: 9,
		LEFT: 37, RIGHT: 39, UP: 38, DOWN: 40,
		DELETE: 46, BACKSPACE:8
	},
	statusCode: {ok:200, error:300, timeout:301}
}

var CURR_TAB = null;
var MAX_TAB = 0;

function ajaxError(error, textStatus, errorThrown,forwordUrl){
	if (error.status == 0){
		alert("服务器访问不到");
		return;
	}
	var errPage = error.responseText.replace("###forwordUrl###",forwordUrl);
	//$('#ajax-content').html(errPage);
	console.debug("error = ",error, textStatus, errorThrown);
	if (error.status == 500){
		loadAjaxContent("error/500.jsp?forwordUrl="+forwordUrl);
	}else if (error.status == 404){
		loadAjaxContent("error/404.jsp?forwordUrl="+forwordUrl);
	}else if (error.status == 0){
		alert("no server resp");
	}else{
		alert("error status = "+error.status+" errorThrown = "+ errorThrown);
	}
}

/**
 * 实现对输入框进行输入提示和查找带回的处理
 */	
$.fn.extend({
	hoverClass: function(className){
		var _className = className || "hover";
		return this.each(function(){
			$(this).hover(function(){
				$(this).addClass(_className);
			},function(){
				$(this).removeClass(_className);
			});
		});
	},
	suggest: function(){
		var op = {suggest$:"#suggest", suggestShadow$: "#suggestShadow"};
		var selectedIndex = -1;
		return this.each(function(){
			var $input = $(this).keydown(function(event){
				if (event.keyCode == UI.keyCode.ENTER) return false; //屏蔽回车提交
			});
			
		
			function _show(){
				var offset = $input.offset();
				var iTop = offset.top+this.offsetHeight;
				var $suggest = $(op.suggest$);
				if ($suggest.size() == 0) $suggest = $('<div id="suggest"></div>').appendTo($('body'));
				
				/*引起界面抖动，去掉
				$suggest.css({
					left:offset.left+'px',
					top:iTop+'px'
				}).show();
				*/
				$.ajax({
					type:"post",
					dataType:"json",
					url:"common/ctrl/suggest",
					data:{"searchClass":$input.attr("searchClass"),"searchField":$input.attr("searchField"),"searchValue":$input.val().trim()},
					success: function(response){
						if (!response) return;
						var offset = $input.offset();
						var iTop = offset.top+$input.height();
						$suggest.css({
							'position': 'absolute',
							'left':offset.left+'px',
							'top':iTop+10+'px',
							'z-index':'101',
							'color' : '#ffffff'
						}).show();	
						var html = "<ul>";
						html = html + "<li inputName='"+$input.attr("id")+"' bringbackValue=''>无</li>";
						$(response).each(function(){
							html = html + "<li inputName='"+$input.attr("id")+"' bringbackValue='"+eval('$(this)[0].'+$input.attr("bringbackField"))+"'>"+eval('$(this)[0].'+$input.attr("searchField"))+"</li>";
						});
						html = html + "</ul>";
						$suggest.html(html).find("li").hoverClass("selected").click(function(){
							_select($(this));
						});
					},
					error: function(res){
						$suggest.html('');
						alert("ajax error status = "+res.status+" error text = " + res.statusText);
					}
				});


				$(document).bind("click", _close);
				return false;
			}
			
			function _select($item){
				//console.debug("suggest : _select : ",$item.attr('bringbackValue'),$item.attr('inputName'),$item.attr('inputName').substring(2));	
				$("#"+$item.attr('inputName')).val($item.text());
				$("#"+$item.attr('inputName').substring(2)).val($item.attr('bringbackValue'));
			}
			function _close(){
				//console.debug("suggest : _close : ",selectedIndex);	
				$(op.suggest$).html('').hide();
				selectedIndex = -1;
				$(document).unbind("click", _close);
			}
			
			
			$input.focus(_show).click(false).keyup(function(event){
				var $items = $(op.suggest$).find("li");
				switch(event.keyCode){
					case UI.keyCode.ESC:
					case UI.keyCode.TAB:
					case UI.keyCode.SHIFT:
					case UI.keyCode.HOME:
					case UI.keyCode.END:
					case UI.keyCode.LEFT:
					case UI.keyCode.RIGHT:
						break;
					case UI.keyCode.ENTER:
						_close();
						break;
					case UI.keyCode.DOWN:
						if (selectedIndex >= $items.size()-1) selectedIndex = -1;
						else selectedIndex++;
						break;
					case UI.keyCode.UP:
						if (selectedIndex < 0) selectedIndex = $items.size()-1;
						else selectedIndex--;
						break;
					default:
						_show();
				}
				$items.removeClass("selected");
				console.debug("suggest : keyup : ",selectedIndex);	
				if (selectedIndex>=0) {
					var $item = $items.eq(selectedIndex).addClass("selected");
					_select($item);
				}
			});
		});
	},
	lookupback:function(){
		var $look = $("#lookupbackDialog");
		
		return this.each(function(){
			var $fieldName;
			$fieldName = $(this).attr("id");
			$fieldName = $fieldName.substring(2);

			var $this = $(this);
			$this.unbind("click").click(function(event){//不写.unbind("click")会导致一次click执行多次function
				_showDialog($this);
				event.preventDefault();
			});
		
			if ($look) {//翻页时，绑定其他页的选择按钮
		    	$(".bringback",$look).each(function(){
		    		var $bringback = $(this);
		    		$bringback.click(function(event){
		    			$("#"+$fieldName).val($bringback.attr("backKey"));
		    			$("#"+"f_"+$fieldName).val($bringback.attr("backValue"));
		    		    $("#lookupbackDialog").html("");
		    		    $("#lookupbackDialog").remove();
		    			
		    			event.preventDefault();
		    		})
		    	});
			}
	    	
			function _showDialog($this){
				var data = {'dlgFlag':1};
				if ($look) {
					$look.html("");
					$look.remove();
				}
				$look = $('<div id="lookupbackDialog"></div>').appendTo($('body'));
		        $.ajax({
		            type: 'post',
		            url: $this.attr("lookupUrl"),
		            data: data,
		            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
		            dataType: 'html',
		            success: function (res) {
		            	$look.html(res);
		    			$look.dialog({
		    				width : "800",
		    				modal: true,
		    				close:function(){
		    					$look.remove();
		    				}
		    			});
		    			//在$look中，查找.bringback
		    	    	$(".bringback",$look).each(function(){
		    	    		var $bringback = $(this);
		    	    		$bringback.click(function(event){
		    	    			$("#"+$fieldName).val($bringback.attr("backKey"));
		    	    			$("#"+"f_"+$fieldName).val($bringback.attr("backValue"));
		    	    		    $("#lookupbackDialog").html("");
		    	    		    $("#lookupbackDialog").remove();
		    	    			
		    	    			event.preventDefault();
		    	    		})
		    	    	});
		    			
		            },
		            error: function (res) {
		                console.debug("_showDialog",res);
						alert("ajax error status = "+res.status+" error text = " + res.statusText);
		            }
		        });			
			}	
		});
	}
});


/**
 * 通过ajax方式实现对页面的加载，本系统中加载到主页面的ajax-content层
 */
/*
function loadAjaxContent(url){
//$('.preloader').show();
	if ("#" == url){
		return;
	}
	$.ajax({
		mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
		url: url,
		type: 'GET',
		success: function(data) {
			$('#ajax-content').html(data);
		},
		error: function (error, textStatus, errorThrown) {
			//alert(errorThrown);
			ajaxError(error, textStatus, errorThrown,'#');
		},
		dataType: "html",
		async: false
	});
}
*/

function loadAjaxContent(url){
	//$('.preloader').show();
		if ("#" == url  || url == null || url == "" || url.length == 0){
			return;
		}
		$.ajax({
			mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
			url: url,
			type: 'GET',
			success: function(data) {
				
				//console.debug(data);
				$('#ajax-content').html(data);
				
				/*
				
				if (true){ //由于多TAB尚未处理完善，不在新TAB打开。另外，还有鼠标滚动式，左侧菜单不跟随的问题
					console.debug(CURR_TAB);
					if ( CURR_TAB == null ){
						CURR_TAB = "tab_container_1";
					}
					console.debug(CURR_TAB);
					$("#"+CURR_TAB).html(data);
				}else{
					
					closableTab.addNewTabWithData("新标签"+MAX_TAB,data);
					
				}
				*/
			},
			error: function (error, textStatus, errorThrown) {
				//alert(errorThrown);
				ajaxError(error, textStatus, errorThrown,'#');
			},
			dataType: "html",
			async: false
		});
}

/**
 * 实现表单提交，包括数据验证和提交成功后的页面跳转
 * @param form
 * @param forwordUrl
 * @returns {Boolean}
 */
function ajaxFormSubmit(form,forwordUrl){

	var $form = $(form);
	if (!$form.valid()) {
		return false;
	}
	//console.debug("test2");
	$(document).mask('处理中...');
	$.ajax({
		type: form.method || 'POST',
		url:$form.attr("action"),
		data:$form.serializeArray(),
		dataType:"json",
		cache: false,
		success: function(data){
			
			if (data.suc == 'n'){
				alert(data.err);
				return;
			}
			
			if ($("#lookupbackDialog")){
				$("#lookupbackDialog").dialog('close');
			}				

			if (forwordUrl != null){
				loadAjaxContent(forwordUrl);
			}
			else{
				alert(data.errorMsg);
			}
		},
		error: function (error, textStatus, errorThrown) {
			ajaxError(error,textStatus,errorThrown,forwordUrl);
		},
		complete:function(){
			$(document).unmask();
		}		
	});
	return false;
	
}

/*
function ajaxPost(url,param){
	$(document).mask('处理中...');

	$.ajax({
		url:url,
		type:'POST',
		data:param,
		success:function(data){
			alert(data.errorMsg);
		},
		error:function(){
			alert('操作失败');
		},
		complete:function(){
			$(document).unmask();
		}
	});
}
*/

function ajaxPostEx(url,param,sucCallbackUrl,errCallbackUrl){
	$(document).mask('处理中...');

	$.ajax({
		url:url,
		type:'POST',
		data:param,
		dataType:"json",
		success:function(data){
			if (data.suc == 'y'){
				alert(data.msg);
				loadAjaxContent(sucCallbackUrl);
			}else if (data.suc == 'n'){
				alert(data.msg);
				loadAjaxContent(errCallbackUrl);
			}
			if (data.errorMsg != null && data.errorMsg != undefined){
				alert(data.errorMsg);
			}
		},
		error:function(){
			alert('操作失败');
		},
		complete:function(){
			$(document).unmask();
		}
	});
}


function ajaxPost(url,param){
	ajaxPostEx(url,param,null,null);
}

/**
 * 实现对遮盖层的处理
 */
$.fn.extend({
    mask: function(msg,maskDivClass){
        this.unmask();
        // 参数
        var op = {
            opacity: 0.8,
            z: 10000,
            bgcolor: '#ccc'
        };
        var original=$(document.body);
        var position={top:0,left:0};
                    if(this[0] && this[0]!==window.document){
                        original=this;
                        position=original.position();
                    }
        // 创建一个 Mask 层，追加到对象中
        var maskDiv=$('<div class="maskdivgen">&nbsp;</div>');
        maskDiv.appendTo(original);
        var maskWidth=original.outerWidth();
        if(!maskWidth){
            maskWidth=original.width();
        }
        maskWidth = $(window).width();
        
        var maskHeight=original.outerHeight();
        if(!maskHeight){
            maskHeight=original.height();
        }
        maskHeight = $(window).height();
        
        maskDiv.css({
            position: 'absolute',
            top: position.top,
            left: position.left,
            'z-index': op.z,
            width: maskWidth + 15,
            height:maskHeight ,
            'background-color': op.bgcolor,
            opacity: 0
        });
        if(maskDivClass){
            maskDiv.addClass(maskDivClass);
        }
        if(msg){
            var msgDiv=$('<div style="position:absolute;border:#6593cf 1px solid; padding:2px;background:#ccca"><div style="line-height:24px;border:#a3bad9 1px solid;background:white;padding:2px 10px 2px 10px">'+msg+'</div></div>');
            msgDiv.appendTo(maskDiv);
            var widthspace=(maskDiv.width()-msgDiv.width());
            var heightspace=(maskDiv.height()-msgDiv.height());
            msgDiv.css({
                        cursor:'wait',
                        top:(heightspace/2-2),
                        left:(widthspace/2-2)
              });
          }
          maskDiv.fadeIn('fast', function(){
            // 淡入淡出效果
            $(this).fadeTo('slow', op.opacity);
        })
        return maskDiv;
    },
    unmask: function(){
             var original=$(document.body);
                 if(this[0] && this[0]!==window.document){
                    original=$(this[0]);
              }
              original.find("> div.maskdivgen").fadeOut('slow',0,function(){
                  $(this).remove();
              });
    }	
})


/**
 * 可关闭的tab对象
 * 使用方式如下：
		var item = {'id':'1','name':'首页','url':'son.html','closable':true};
		closableTab.addTab(item); * 
 */
var closableTab = {

	
	curr:function(item){
		var val = $(item).attr('tabclose');
		CURR_TAB = "tab_container_"+val.substring(9);
		console.debug("currContainer = " + CURR_TAB);
	},
	
    //添加tab
	addTab:function(tabItem){ //tabItem = {id,name,url,closable}
		
		MAX_TAB++;
		
		console.debug("tabItem",tabItem);
		var id = "tab_seed_" + tabItem.id;
		var container ="tab_container_" + tabItem.id;

		$("li[id^=tab_seed_]").removeClass("active");
		$("div[id^=tab_container_]").removeClass("active");

		console.debug("$('#'+id)[0]",$('#'+id)[0]);

		if(!$('#'+id)[0]){
			var li_tab = '<li role="presentation" class="" id="'+id+'"><a href="#'+container+'"  tabclose="'+id+'" role="tab" data-toggle="tab" style="position: relative;padding:2px 20px 2px 15px" onclick=closableTab.curr(this)>'+tabItem.name;
			if(tabItem.closable){
				li_tab = li_tab + '<i class="glyphicon glyphicon-remove small" tabclose="'+id+'" style="position: absolute;right:4px;top: 4px;"  onclick="closableTab.closeTab(this)"></i></a></li> ';
			}else{
				li_tab = li_tab + '</a></li>';
			}
		
		 	var tabpanel = '<div role="tabpanel" class="tab-pane" id="'+container+'" style="width: 100%;">'+
	    					  '正在加载...'+
	    				   '</div>';


			$('.nav-tabs').append(li_tab);
			$('.tab-content').append(tabpanel);
			
			/*
			$('#'+container).load(tabItem.url,function(response,status,xhr){
				if(status=='error'){//status的值为success和error，如果error则显示一个错误页面
					$(this).html(response);
				}
			});
			*/
			$.ajax({
				mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
				url: tabItem.url,
				type: 'GET',
				success: function(data) {
					
					$('#'+container).html(data);
				},
				error: function (error, textStatus, errorThrown) {
					//alert(errorThrown);
					ajaxError(error, textStatus, errorThrown,'#');
				},
				dataType: "html",
				async: false
			});
			
			
		}
		$("#"+id).addClass("active");
		$("#"+container).addClass("active");
	},
	
    //添加tab
	addNewTabWithData:function(tabName,data){ //tabItem = {id,name,url,closable,data}

		MAX_TAB++;

		var id = "tab_seed_" + MAX_TAB;
		var container ="tab_container_" + MAX_TAB;

		$("li[id^=tab_seed_]").removeClass("active");
		$("div[id^=tab_container_]").removeClass("active");

		console.debug("$('#'+id)[0]",$('#'+id)[0]);

		if(!$('#'+id)[0]){
			var li_tab = '<li role="presentation" class="" id="'+id+'"><a href="#'+container+'"  tabclose="'+id+'" role="tab" data-toggle="tab" style="position: relative;padding:2px 20px 2px 15px" onclick=closableTab.curr(this)>'+tabName;
			li_tab = li_tab + '<i class="glyphicon glyphicon-remove small" tabclose="'+id+'" style="position: absolute;right:4px;top: 4px;"  onclick="closableTab.closeTab(this)"></i></a></li> ';
		 	var tabpanel = '<div role="tabpanel" class="tab-pane" id="'+container+'" style="width: 100%;">'+
	    					  '正在加载...'+
	    				   '</div>';


			$('.nav-tabs').append(li_tab);
			$('.tab-content').append(tabpanel);
			
			/*
			$('#'+container).load(tabItem.url,function(response,status,xhr){
				if(status=='error'){//status的值为success和error，如果error则显示一个错误页面
					$(this).html(response);
				}
			});
			*/
			console.debug($('#'+container).html());
			console.debug(data);
			$('#'+container).html(data);
			console.debug($('#'+container).html());
			
			
		}
		$("#"+id).addClass("active");
		$("#"+container).addClass("active");
	},	

	//关闭tab
	closeTab:function(item){
		var val = $(item).attr('tabclose');
		var containerId = "tab_container_"+val.substring(9);
   	    
   	    if($('#'+containerId).hasClass('active')){
   	    	$('#'+val).prev().addClass('active');
   	    	$('#'+containerId).prev().addClass('active');
   	    }

		$("#"+val).remove();
		$("#"+containerId).remove();
	}
}


/**
 * 以模态对话框方式打开网页。
 * @param url
 * @param param
 */
function openDialog(url){
	openDialog(url,null,"lookupbackDialog");
}

/**
 * 以模态对话框方式打开网页。
 * @param url
 * @param param
 */
function openDialog(url,param){
	openDialog(url,param,"lookupbackDialog");
}

/**
 * 以模态对话框方式打开网页。
 * @param url
 * @param param
 * @param param
 */
function openDialog(url,param,dialogDivId){
	console.debug("dialogDivId",url,dialogDivId);
	if (!dialogDivId){
		dialogDivId = "lookupbackDialog";
	}
	var $dialog;
	if ($dialog) {
		$dialog.html("");
		$dialog.remove();
	}
	$dialog = $('<div id="'+dialogDivId+'"></div>').appendTo($('body'));	
    $.ajax({
        type: 'post',
        url: url,
        data: param,
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        dataType: 'html',
        success: function (res) {
        	$dialog.html(res);
        	$dialog.dialog({
				width : $(window).width() -200,
				modal: true,
				close:function(){
					$dialog.remove();
				}
			});
        },
        error: function (res) {
            console.debug("_showDialog",res);
			alert("ajax error status = "+res.status+" error text = " + res.statusText);
        }
    });		
}